package ar.uba.fi.tonyvaliente.web.manager;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ar.uba.fi.tonyvaliente.commands.CommandResult;
import ar.uba.fi.tonyvaliente.documents.AddDocumentResult;
import ar.uba.fi.tonyvaliente.documents.DocumentManager;
import ar.uba.fi.tonyvaliente.signature.HashFunction;
import ar.uba.fi.tonyvaliente.signature.SignatureConfiguration;
import ar.uba.fi.tonyvaliente.signature.SignatureConfigurationException;
import ar.uba.fi.tonyvaliente.signature.process.CreateSignatureResult;
import ar.uba.fi.tonyvaliente.signature.process.SignatureGenerator;
import ar.uba.fi.tonyvaliente.utils.RecursosAplicacion;

public class DocumentAddManager {

	private static Log log = LogFactory.getLog(DocumentAddManager.class);
	
	private String message;
	
	public boolean addDocument(String path, String index){
		
		boolean success;
		if(index.equalsIgnoreCase("BPlusTree")){
			success = addDocumentToBPlusTree(path);
		}else{
			success = addDocumentToSignatureFile(path);
		}
		
		return success;
	}
	
	private boolean addDocumentToBPlusTree(String path){
		boolean success = true;
		
		AddDocumentResult result = DocumentManager.addDocument(path);
		if(result.isSuccess()){
			log.info("Document Added");
			message = "The document "+ path +" has been added to the index.";
		}else{
			log.info("Document Not Added");
			message = "An error ocurred: " + result.getErrorMessage();
			success = addDocumentToSignatureFile(path);
		}
		
		return success;
		
	}
	
	private boolean addDocumentToSignatureFile(String path){
		boolean success = true;
		
		String configurationPath = RecursosAplicacion.instance().getProperty("hash.config");
		
		SignatureConfiguration config = null;
		try {
			config = SignatureConfiguration.loadFromFile(configurationPath);
		} catch (SignatureConfigurationException e) {
			e.printStackTrace();
			success = false;
			message = "An error ocurred: " + e.getMessage();
		}
		
		List<HashFunction> hashFunctions = new ArrayList<HashFunction>(config.getHashFunctions());
		int length = config.getSignatureLength();
		
		CreateSignatureResult createSignatureResult = SignatureGenerator.process(path, hashFunctions, length);
		if (createSignatureResult.isSuccess()){
			success = true;
			message = "The document "+ path +" has been added to the index.";
		}else{
			success = false;
			message = "An error ocurred: " + createSignatureResult.getErrorMessage();
		}
		
		return success;
		
	}
	
	public String getMessage(){
		return message;
	}
}
